package cn.sciento.websocket.autoconfigure;

import cn.sciento.websocket.config.WebSocketConfig;
import cn.sciento.websocket.handler.WebSocketHandler;
import cn.sciento.websocket.interceptor.WebSocketInterceptor;
import cn.sciento.websocket.listener.RedisListener;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;

@Configuration
@EnableWebSocket
@ComponentScan(basePackages = {"cn.sciento.websocket"})
public class WebSocketAutoConfig implements WebSocketConfigurer {
    private WebSocketConfig config;

    public WebSocketAutoConfig(WebSocketConfig config) {
        this.config = config;
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new WebSocketHandler(this.config), this.config.getWebsocket()).addInterceptors(new WebSocketInterceptor()).setAllowedOrigins("*");
        registry.addHandler(new WebSocketHandler(this.config), this.config.getSockJs()).addInterceptors(new WebSocketInterceptor()).setAllowedOrigins("*").withSockJS();
    }

    @Bean({"ws-adapter"})
    MessageListenerAdapter listenerAdapter(RedisListener listener) {
        return new MessageListenerAdapter(listener, "messageListener");
    }

    @Bean({"ws-container"})
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, @Qualifier("ws-adapter") MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic("stong-webSocket"));
        return container;
    }
}
